package com.auto.qinglong.net.client

import android.util.Log
import com.auto.qinglong.net.client.beans.LoginBean
import com.auto.qinglong.net.client.beans.QlAccount
import com.auto.qinglong.net.client.beans.SystemInfo
import com.auto.qinglong.net.client.beans.TaskGroupTagBean
import com.auto.qinglong.net.client.beans.TaskResultBean
import com.auto.qinglong.net.panel.DependenceLogRes
import com.auto.qinglong.net.panel.FileContentRes
import com.auto.qinglong.net.panel.LoginLogsRes
import com.auto.qinglong.net.panel.LoginRes
import com.auto.qinglong.net.panel.v15.SystemConfigRes
import com.google.gson.JsonElement
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import okhttp3.RequestBody
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.HTTP
import retrofit2.http.Header
import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Path
import retrofit2.http.Query
import retrofit2.http.Url

fun <T> CoroutineScope.loadHttp(
    // 默认实现{}，即参数可空
    start: suspend () -> Unit = {},
    // suspend 修饰的函数，返回值ResultData<T>，没有默认实现，即参数不可空
    request: suspend CoroutineScope.() -> Call<BaseBean<T>>?,
    // 函数的参数为T，没有默认实现，即参数不可空
    response: (T) -> Unit = { },
    response2: () -> Unit = { },
    error: (Int, String) -> Unit = { _: Int, _: String -> },
    end: () -> Unit = {}
): Job {
    // 在主线程(Dispatchers.Main)执行
    return launch(Dispatchers.Main) {
        try {
            start()
            // 2.发起网络请求
            val result = request()

            (result as? BaseBean<T>)?.let {
                if (result.code == 200) {
                    result.data?.let {
                        response(it)
                    } ?: run {
                        response2()
                    }
                } else {
                    error(result.code, result.message)
                }
            } ?: (result)
        } catch (e: Exception) {
            Log.e("http", e.message ?: "")
            // 可根据具体异常显示具体错误提示
        } finally {
            end()
        }
    }
}


/**
 * Created by YuanWei1 on 2025/6/12.
 *
 * Description:
 */
interface ApiQl {
    //    登录
    @POST("api/user/login")
    suspend fun login(@Body user: QlAccount): BaseBean<LoginBean>

    //    获取任务列表
    @GET("api/crons")
    suspend fun getTasks(
        @Query("searchValue") searchValue: String?,
        @Query("page") page: Int,
        @Query("size") size: Int,
        @Query("queryString") queryString: String
    ): BaseBean<TaskResultBean>

    //    执行任务
    @PUT("api/crons/run")
    suspend fun runTasks(@Body body: List<String>): BaseBean<JsonElement>

    //    置顶
    @PUT("api/crons/pin")
    suspend fun pinTasks(@Body body: RequestBody?): BaseBean<String?>?

    //    取消置顶
    @PUT("api/crons/unpin")
    suspend fun unpinTasks(@Body body: RequestBody?): BaseBean<String?>?

    //    任务分组标签
    @GET("api/crons/views")
    suspend fun getViews(): BaseBean<List<TaskGroupTagBean>>

    @GET("api/crons/{taskId}/log")
    suspend fun getTaskLog(@Path("taskId") taskId: String): BaseBean<String>

    @HTTP(method = "DELETE", path = "api/crons", hasBody = true)
    suspend fun deleteTasks(@Body body: RequestBody): BaseBean<String>

    @GET("api/system")
    suspend fun getSystemInfo(): Call<BaseBean<SystemInfo>>

    @PUT("api/user/init")
    fun initAccount(@Body body: RequestBody?): BaseBean<String?>?

    @PUT("api/user/two-factor/login")
    fun twoFactorLogin(@Body body: RequestBody?): BaseBean<LoginRes?>?


    @PUT("api/crons/stop")
    fun stopTasks(@Body body: RequestBody?): BaseBean<String?>?

    @PUT("api/crons/enable")
    fun enableTasks(@Body body: RequestBody?): BaseBean<String?>?

    @PUT("api/crons/disable")
    fun disableTasks(@Body body: RequestBody?): BaseBean<String?>?


    @POST("api/crons")
    fun addTask(@Body body: RequestBody?): BaseBean<String?>?

    @PUT("api/crons")
    fun updateTask(@Body body: RequestBody?): BaseBean<String?>?


    @PUT("api/envs/enable")
    fun enableEnvironments(@Body body: RequestBody?): BaseBean<String?>?

    @PUT("api/envs/disable")
    fun disableEnvironments(@Body body: RequestBody?): BaseBean<String?>?

    @PUT("api/envs")
    fun updateEnvironment(@Body body: RequestBody?): BaseBean<String?>?

    @POST("api/envs")
    fun addEnvironments(@Body body: RequestBody?): BaseBean<String?>?

    @HTTP(method = "DELETE", path = "api/envs", hasBody = true)
    fun deleteEnvironments(@Body body: RequestBody?): BaseBean<String?>?

    @POST("api/dependencies")
    fun addDependencies(@Body body: RequestBody?): BaseBean<String?>?

    @PUT("api/dependencies/reinstall")
    fun reinstallDependencies(@Body body: RequestBody?): BaseBean<String?>?

    @GET
    fun getDependenceLog(@Url url: String?): BaseBean<DependenceLogRes?>?

    @POST("api/configs/save")
    fun updateConfigContent(@Body body: RequestBody?): BaseBean<String?>?

    @PUT("api/scripts")
    fun updateScript(@Body body: RequestBody?): BaseBean<String?>?

    @HTTP(method = "DELETE", path = "api/scripts", hasBody = true)
    fun deleteScript(@Body body: RequestBody?): BaseBean<String?>?

    @GET("api/user/login-log")
    fun getLoginLogs(): BaseBean<LoginLogsRes?>?

    @GET
    fun getFileContent(@Url url: String?): BaseBean<FileContentRes?>?

    @PUT("api/user")
    fun updateAccount(@Body body: RequestBody?): BaseBean<String>

    @GET("api/system/config")
    fun getSystemConfig(): BaseBean<SystemConfigRes?>?

    @GET("api/system/config")
    fun checkToken(@Header("Authorization") token: String?): BaseBean<SystemConfigRes?>?
}